package com.murong.ai.coder.infrastructure.view;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.murong.ai.coder.entity.DbConfig;
import com.murong.ai.coder.entity.GlobalProperties;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.Properties;

public class InterfaceQueryWindow extends JFrame {
    private JTextField searchField;
    private JTable resultTable;
    private JTextArea reqParamsArea;
    private JTextArea rspParamsArea;
    private JButton searchButton;
    private JButton saveButton;
    private JComboBox<String> sessionFlagCombo;
    private Map<String, DbConfig> envDbConfigMap = new HashMap<>();
    private String currentId;
    private final ObjectMapper objectMapper;

    public InterfaceQueryWindow() {
        // 初始化JSON格式化工具
        objectMapper = new ObjectMapper();
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        
        // 修改数据库连接URL，添加额外参数
        String jdbcUrl = "jdbc:postgresql://182.188.5.117:25432/cbp_mbl_banking";
                
        DbConfig dbConfig = new DbConfig("org.postgresql.Driver",
                jdbcUrl, "cgdcgw", "cgdcgw@123");
        envDbConfigMap.put("dev", dbConfig);
        initUI();
    }

    private void initUI() {
        setTitle("接口信息查询与更新");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(1200, 800);
        setLocationRelativeTo(null);

        // 主面板
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchField = new JTextField(30);
        searchButton = new JButton("查询");
        saveButton = new JButton("保存");
        saveButton.setEnabled(false);
        
        // 添加session标识下拉框
        sessionFlagCombo = new JComboBox<>(new String[]{"否", "是"});
        sessionFlagCombo.setEnabled(false);
        
        searchPanel.add(new JLabel("接口路径:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);
        searchPanel.add(new JLabel("Session标识:"));
        searchPanel.add(sessionFlagCombo);
        searchPanel.add(saveButton);
        mainPanel.add(searchPanel, BorderLayout.NORTH);

        // 结果表格
        resultTable = new JTable();
        JScrollPane tableScrollPane = new JScrollPane(resultTable);
        
        // 参数编辑面板 - 左右布局
        JPanel paramsPanel = new JPanel(new GridLayout(1, 2, 10, 0));
        
        // 请求参数面板
        JPanel reqPanel = new JPanel(new BorderLayout());
        reqPanel.setBorder(BorderFactory.createTitledBorder("请求参数"));
        reqParamsArea = new JTextArea();
        reqParamsArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        JScrollPane reqScrollPane = new JScrollPane(reqParamsArea);
        reqPanel.add(reqScrollPane, BorderLayout.CENTER);
        
        // 响应参数面板
        JPanel rspPanel = new JPanel(new BorderLayout());
        rspPanel.setBorder(BorderFactory.createTitledBorder("响应参数"));
        rspParamsArea = new JTextArea();
        rspParamsArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        JScrollPane rspScrollPane = new JScrollPane(rspParamsArea);
        rspPanel.add(rspScrollPane, BorderLayout.CENTER);
        
        paramsPanel.add(reqPanel);
        paramsPanel.add(rspPanel);

        // 使用JSplitPane来分割表格和参数面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tableScrollPane, paramsPanel);
        splitPane.setResizeWeight(0.3); // 设置分割比例，表格占30%，参数面板占70%
        splitPane.setDividerLocation(150); // 设置初始分割位置
        
        mainPanel.add(splitPane, BorderLayout.CENTER);

        // 添加事件监听
        searchButton.addActionListener(e -> performSearch());
        saveButton.addActionListener(e -> saveChanges());
        
        resultTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = resultTable.getSelectedRow();
                if (row >= 0) {
                    currentId = resultTable.getValueAt(row, 0).toString();
                    String reqParams = resultTable.getValueAt(row, 3).toString();
                    String rspParams = resultTable.getValueAt(row, 4).toString();
                    try {
                        // 格式化JSON
                        reqParamsArea.setText(formatJson(reqParams));
                        rspParamsArea.setText(formatJson(rspParams));
                        saveButton.setEnabled(true);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(InterfaceQueryWindow.this,
                                "JSON格式化失败：" + ex.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });

        getContentPane().add(mainPanel);
        setVisible(true);
    }

    private void performSearch() {
        String searchValue = searchField.getText().trim();
        DbConfig config = envDbConfigMap.get("dev"); // 使用开发环境配置

        String sql = "select id,gw_req_path,backend_req_path,req_params,rsp_params,session_flg " +
                    "from cgdcgw.t_cgw_interface_inf a where gateway_id='app' and gw_req_path like ?";

        try {
            Class.forName(config.getDriver());
            
            // 设置连接属性
            Properties props = new Properties();
            props.setProperty("user", config.getUsername());
            props.setProperty("password", config.getPassword());
            props.setProperty("ssl", "false");
            props.setProperty("ApplicationName", "InterfaceQuery");
            props.setProperty("preferQueryMode", "simple");
            
            try (Connection conn = DriverManager.getConnection(config.getUrl(), props);
                 PreparedStatement stmt = conn.prepareStatement(sql)) {
                
                stmt.setString(1, "%" + searchValue + "%");
                
                try (ResultSet rs = stmt.executeQuery()) {
                    showResultSetWithSelection(rs);
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,
                    "查询出错：" + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }

    private void saveChanges() {
        if (currentId == null) {
            JOptionPane.showMessageDialog(this,
                    "请先选择一条记录！",
                    "提示",
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        String reqParams = reqParamsArea.getText().trim();
        String rspParams = rspParamsArea.getText().trim();
        String sessionFlg = sessionFlagCombo.getSelectedIndex() == 1 ? "1" : "0";

        // 验证JSON格式
        try {
            objectMapper.readTree(reqParams);
            objectMapper.readTree(rspParams);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "JSON格式无效：" + e.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }

        DbConfig config = envDbConfigMap.get("dev"); // 使用开发环境配置

        String sql = "update cgdcgw.t_cgw_interface_inf set req_params=?, rsp_params=?, session_flg=? where id=? and gateway_id='app'";

        try {
            Class.forName(config.getDriver());
            
            // 设置连接属性
            Properties props = new Properties();
            props.setProperty("user", config.getUsername());
            props.setProperty("password", config.getPassword());
            props.setProperty("ssl", "false");
            props.setProperty("ApplicationName", "InterfaceQuery");
            props.setProperty("preferQueryMode", "simple");
            
            try (Connection conn = DriverManager.getConnection(config.getUrl(), props);
                 PreparedStatement stmt = conn.prepareStatement(sql)) {
                
                stmt.setString(1, formatJsonWithoutIndent(reqParams));
                stmt.setString(2, formatJsonWithoutIndent(rspParams));
                stmt.setString(3, sessionFlg);
                stmt.setString(4, currentId);

                int result = stmt.executeUpdate();
                if (result > 0) {
                    // 清空参数面板和重置UI状态
                    reqParamsArea.setText("");
                    rspParamsArea.setText("");
                    saveButton.setEnabled(false);
                    sessionFlagCombo.setEnabled(false);
                    sessionFlagCombo.setSelectedIndex(0);
                    currentId = null;
                    
                    try (PreparedStatement queryStmt = conn.prepareStatement(
                            "select id,gw_req_path,backend_req_path,req_params,rsp_params,session_flg " +
                            "from cgdcgw.t_cgw_interface_inf a where gateway_id='app' and gw_req_path like ?")) {
                        queryStmt.setString(1, "%" + searchField.getText().trim() + "%");
                        try (ResultSet rs = queryStmt.executeQuery()) {
                            showResultSet(rs); // 使用不自动选择的版本
                        }
                    }
                    
                    JOptionPane.showMessageDialog(this,
                            "更新成功！",
                            "成功",
                            JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this,
                            "更新失败：未找到记录",
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,
                    "更新出错：" + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }

    private void showResultSet(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        
        // 设置列名
        Vector<String> columnNames = new Vector<>();
        for (int i = 1; i <= columnCount; i++) {
            columnNames.add(metaData.getColumnName(i));
        }
        
        // 设置数据
        Vector<Vector<Object>> data = new Vector<>();
        while (rs.next()) {
            Vector<Object> row = new Vector<>();
            for (int i = 1; i <= columnCount; i++) {
                row.add(rs.getObject(i));
            }
            data.add(row);
        }
        
        DefaultTableModel model = new DefaultTableModel(data, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 使表格不可编辑
            }
        };
        
        resultTable.setModel(model);
        
        if (data.isEmpty()) {
            JOptionPane.showMessageDialog(this,
                    "未找到匹配的记录！",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE);
            // 清空参数面板
            reqParamsArea.setText("");
            rspParamsArea.setText("");
            saveButton.setEnabled(false);
            sessionFlagCombo.setEnabled(false);
            currentId = null;
        }
    }

    private void showResultSetWithSelection(ResultSet rs) throws SQLException {
        showResultSet(rs);
        if (resultTable.getRowCount() > 0) {
            // 自动选择第一行并显示其参数数据
            resultTable.setRowSelectionInterval(0, 0);
            Vector<Object> firstRow = ((DefaultTableModel)resultTable.getModel()).getDataVector().get(0);
            currentId = firstRow.get(0).toString();
            try {
                String reqParams = firstRow.get(3).toString();
                String rspParams = firstRow.get(4).toString();
                String sessionFlg = firstRow.get(5).toString();
                reqParamsArea.setText(formatJsonWithIndent(reqParams));
                rspParamsArea.setText(formatJsonWithIndent(rspParams));
                sessionFlagCombo.setSelectedIndex("1".equals(sessionFlg) ? 1 : 0);
                saveButton.setEnabled(true);
                sessionFlagCombo.setEnabled(true);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this,
                        "JSON格式化失败：" + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private String formatJson(String json) throws Exception {
        Object jsonObj = objectMapper.readValue(json, Object.class);
        return objectMapper.writeValueAsString(jsonObj);
    }

    /**
     * 格式化JSON并保留换行符
     */
    private String formatJsonWithIndent(String json) throws Exception {
        Object jsonObj = objectMapper.readValue(json, Object.class);
        return objectMapper.writeValueAsString(jsonObj);
    }

    /**
     * 格式化JSON并移除换行符
     */
    private String formatJsonWithoutIndent(String json) throws Exception {
        Object jsonObj = objectMapper.readValue(json, Object.class);
        // 临时禁用美化输出
        objectMapper.disable(SerializationFeature.INDENT_OUTPUT);
        String result = objectMapper.writeValueAsString(jsonObj);
        // 重新启用美化输出
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        return result;
    }

    public static void main(String[] args) {
        // 使用SwingUtilities确保在EDT线程中创建和显示GUI
        SwingUtilities.invokeLater(() -> {
            try {
                // 设置本地系统外观
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            new InterfaceQueryWindow();
        });
    }
} 